package com.example.service;

import cn.hutool.json.JSONObject;
import com.example.common.Result;
import com.example.entity.MedicationLogs;
import com.example.mapper.MedicationLogsMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Service
public class MedicationLogsService {

    @Resource
    private MedicationLogsMapper medicationLogsMapper;
    public Result upMedication(MedicationLogs medicationLogs) {
        // 获取当前日期的年月日部分
        LocalDate today = LocalDate.now();
        // 将LocalDate转换为Date对象（时间部分为00:00:00）
        Date date = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
        medicationLogs.setLogDate(date);
        MedicationLogs old = medicationLogsMapper.getByUserIdDateMedId(medicationLogs);
        if(medicationLogs.getMedId() == null || medicationLogs.getUserId() == null){
            return Result.error("用户Id或药品Id不能为空");
        }
        if(old!=null){
            if(!medicationLogsMapper.up(medicationLogs)){
                return Result.error("打卡失败");
            }
            return Result.success("打卡成功");
        }
        if(!medicationLogsMapper.add(medicationLogs)){
            return Result.error("打卡失败");
        }
        return Result.success("打卡成功");
    }

    public Result list(MedicationLogs medicationLogs) {
        List<JSONObject> result = medicationLogsMapper.list(medicationLogs);
        return Result.success(result);
    }

    public Result listAll() {
        List<MedicationLogs> medicationLogsList = medicationLogsMapper.listAll();
        return Result.success(medicationLogsList);
    }

    public Result listToday(MedicationLogs medicationLogs) {
// 获取当前日期的年月日部分
        LocalDate today = LocalDate.now();
        // 将LocalDate转换为Date对象（时间部分为00:00:00）
        Date date = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
        medicationLogs.setLogDate(date);
        List<JSONObject> result = medicationLogsMapper.listToday(medicationLogs);
        return Result.success(result);
    }
}
